//
//  LCVideoViewController.m
//  TheLCNews
//
//  Created by apple on 15/11/26.
//  Copyright © 2015年 LC. All rights reserved.
//

#import "LCVideoViewController.h"
#import "LCVideoTbCell.h"
#import "LCVideoModel.h"
//#import "LYLSingleton.h"
#import <MediaPlayer/MediaPlayer.h>

@interface LCVideoViewController ()<UITableViewDataSource,UITableViewDelegate,MBProgressHUDDelegate>

{
    NSInteger _count;
}
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *array;
@property (nonatomic, assign) NSInteger nextPage;
@property (nonatomic, assign) NSInteger  index;
@property (nonatomic, strong) MPMoviePlayerController *player;
@property (nonatomic, strong) NSURL *str;
@property (nonatomic, strong) UIButton *closeButton;
@property (nonatomic, strong) MBProgressHUD *hud;
@property (nonatomic, strong) MBProgressHUD *hudTwo;

@end

@implementation LCVideoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self creatTableView];
   
    [self getData];
    [self header];
    _count = 10;
}

#pragma mark - 初始化(这里初始化数组)
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.array = [NSMutableArray array];
    }
    return self;
}

#pragma mark - 创建 tableview
- (void)creatTableView
{
    self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:0];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.mj_footer = [MJRefreshAutoStateFooter footerWithRefreshingTarget:self refreshingAction:@selector(fotter)];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.rowHeight = WIDTH / 1.2 + 20;
    
    [self.view addSubview:_tableView];
}

#pragma mark - 返回个数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.array.count;
}

#pragma mark - 重用机制
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *reuse = @"cell";
    LCVideoTbCell *cell = [tableView dequeueReusableCellWithIdentifier:reuse];
    if (cell == nil) {
        cell = [[LCVideoTbCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:reuse];
    }
    LCVideoModel *model = self.array[indexPath.row];
    cell.model = model;
    cell.tag = 1000 + indexPath.row;
    
    
    
    return cell;
}

#pragma mark - 网络请求
- (void)getData
{
    self.hud = [[MBProgressHUD alloc] initWithView:self.tableView];
    [self.view addSubview:_hud];
    [self.view bringSubviewToFront:_hud];
    self.hud.delegate = self;
    self.hud.labelText = @"加载中...";
    [self.hud show:YES];
       //hud.mode = MBProgressHUDModeText;
    [LYLAFNetWorking GETURLByString:VideoURL AFData:^(id result) {
        NSDictionary *dic = result;
        NSArray *arr = dic[@"videoList"];
        self.array = [LCVideoModel baseModelByArr:arr];
        
        if (self.array.count > 0) {
            [self.tableView reloadData];
        }
        [self.tableView.mj_header endRefreshing];
        [self.hud removeFromSuperview];
    }];
}

#pragma mark - 下拉加载
- (void)header
{
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self getData];
        [self.player stop];
        [self.player.view removeFromSuperview];
    } ];
    
}

#pragma mark -上啦刷新
- (void)fotter
{
    static NSInteger count = 10;
    count +=10;
    if ([self.tableView.mj_footer isRefreshing]) {
        [LYLAFNetWorking GETURLByString:[NSString stringWithFormat:@"http://c.3g.163.com/nc/video/home/%ld-10.html",(long)count] AFData:^(id result) {
            NSDictionary *dic = result;
            NSArray *arr = dic[@"videoList"];
            NSMutableArray *temp = [NSMutableArray array];
            temp = [LCVideoModel baseModelByArr:arr];
            [self.array addObjectsFromArray:temp];
            if (self.array.count > 0) {
                [self.tableView reloadData];
            }
        }];
        [self.tableView.mj_footer endRefreshing];
    }
}

- (void)createData:(NSInteger)page{
    //    count ++;
    //self.tableView.mj_footer = [MJRefreshAutoNormalFooter
    if ([self.tableView.mj_footer isRefreshing]) {
        [LYLAFNetWorking GETURLByString:[NSString stringWithFormat:@"http://c.3g.163.com/nc/video/home/%ld-10.html",(long)page] AFData:^(id result) {
            NSDictionary *dic = result;
            NSArray *arr = dic[@"videoList"];
            NSMutableArray *temp = [NSMutableArray array];
            temp = [LCVideoModel baseModelByArr:arr];
            [self.array addObjectsFromArray:temp];
            if (self.array.count > 0) {
                [self.tableView reloadData];
            }
            //}];
            
        }];
    }
}

#pragma mark - 点击事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self.player.view removeFromSuperview];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(exitFullScreen:) name: MPMoviePlayerDidExitFullscreenNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(jionFullScreen:) name:MPMoviePlayerWillEnterFullscreenNotification object:nil];
    
    
    self.index = indexPath.row;
    LCVideoModel *model = self.array[indexPath.row];
    self.str = [NSURL URLWithString:model.mp4_url];
    [self playVieo];
    
    
}




#pragma mark -tableView 滑动 (通过判断 偏移量 出现小窗口视频)
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (self.player.playbackState == MPMoviePlaybackStatePlaying) {
        
    
    if ((self.index - 1)* self.tableView.rowHeight  + self.tableView.contentOffset.y > self.index * HEIGHT + HEIGHT - HEIGHT / 2) {
        self.player.view.frame = CGRectMake(WIDTH / 2,HEIGHT * 2/3 , WIDTH / 2, HEIGHT / 4);
        self.closeButton.frame = CGRectMake(self.player.view.frame.size.width - 35, 10, 30, 30);
        [self.view addSubview:self.player.view];
        
    }
    else if ((self.index - 1)* self.tableView.rowHeight  + self.tableView.contentOffset.y  < self.index * HEIGHT + HEIGHT - HEIGHT / 2) {
        LCVideoTbCell *cell = (LCVideoTbCell *)[self.view viewWithTag:1000 + self.index];
        //self.player.view.frame = cell.picView.bounds;
        self.player.view.frame = CGRectMake(17,self.tableView.rowHeight * self.index + 10, WIDTH - 34, WIDTH / 2);
        self.closeButton.frame = CGRectMake(self.player.view.frame.size.width - 35, 10, 30, 30);
        [self.tableView addSubview:self.player.view];
        
       }
        
    }
    
}


- (void)playVieo {
    
    LCVideoTbCell *cell = (LCVideoTbCell *)[self.view viewWithTag:1000 + self.index];
    self.player = [[MPMoviePlayerController alloc] initWithContentURL:self.str];
    [self.player prepareToPlay];
    [self.tableView addSubview:self.player.view];
    self.player.shouldAutoplay = YES;
    
    //[self.player setControlStyle:MPMovieControlStyleNone];
    [self.player setFullscreen:NO];
    
    [self.player.view setFrame:cell.picView.bounds];
    self.player.view.frame = CGRectMake(17,self.tableView.rowHeight * self.index + 10, WIDTH - 34, WIDTH / 2);
    self.closeButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.closeButton.frame = CGRectMake(self.player.view.frame.size.width - 35, 10, 30, 30);
    [self.closeButton setBackgroundImage:[UIImage imageNamed:@"iconfont-guanbi"] forState:UIControlStateNormal];
    [self.closeButton addTarget:self action:@selector(closeMovie:) forControlEvents:UIControlEventTouchUpInside];
    [self.player.view addSubview:self.closeButton];
    [self addNotification];
 
}

-(void)exitFullScreen:(NSNotification *)notification{
//    [self.player.view removeFromSuperview];
    [self.player play];
}

-(void)jionFullScreen:(NSNotification *)notification{
    //    [self.player.view removeFromSuperview];
    [self.player play];
}


- (void)closeMovie:(UIButton *)button {
    [self.player stop];
    [self.player pause];
    [self.player.view removeFromSuperview];
}

#pragma mark - 控制器通知
- (void)addNotification
{
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(mediaPlayerPlaybackStateChange:) name:MPMoviePlayerPlaybackStateDidChangeNotification object:self.player];
     [center addObserver:self selector:@selector(mediaPlayerPlaybackFinished:) name:MPMoviePlayerPlaybackDidFinishNotification object:self.player];
}

- (void)mediaPlayerPlaybackStateChange:(NSNotification *)nsnotification
{
    switch (self.player.playbackState) {
        case MPMoviePlaybackStatePlaying: {
            [self.hudTwo removeFromSuperview];
            NSLog(@"正在播放...");
        } break;
        case MPMoviePlaybackStatePaused:
            NSLog(@"暂停播放.");
            break;
        case MPMoviePlaybackStateStopped:
            NSLog(@"停止播放.");
            break;
        default:
            NSLog(@"播放状态:%li",(long)self.player.playbackState);
            break;
    }

}

-(void)mediaPlayerPlaybackFinished:(NSNotification *)notification{
    NSLog(@"播放完成.%li",(long)self.player.playbackState);
    [self.player stop];
    [self.player pause];
    [self.player.view removeFromSuperview];
}

- (void)dealloc
{
 [[NSNotificationCenter defaultCenter] removeObserver:self];
}





- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
